package com.zimmur.app.mocolink.domain.util;

/**
 * tweeter的snowflake 移植到Java:
 *   (a) id构成: 42位的时间前缀 + 10位的节点标识 + 12位的sequence避免并发的数字(12位不够用时强制得到新的时间前缀)
 *       注意这里进行了小改动: snowkflake是5位的datacenter加5位的机器id; 这里变成使用10位的机器id
 *   (b) 对系统时间的依赖性非常强，需关闭ntp的时间同步功能。当检测到ntp时间调整后，将会拒绝分配id
 */
public final class IdWorker {
    private final long workerId;
    private final static long twepoch =1463394197000L;// 时间起始标记点，作为基准，一般取系统的最近时间
    private long sequence = 0L; // 0，并发控制
    private final static long workerIdBits = 10L;
    public final static long maxWorkerId = -1L ^ -1L << workerIdBits; // 机器ID最大值: 1023
    private final static long sequenceBits = 12L; //毫秒内自增位
 
    private final static long workerIdShift = sequenceBits; // 12
    private final static long timestampLeftShift = sequenceBits + workerIdBits; // 22
    public final static long sequenceMask = -1L ^ -1L << sequenceBits; // 4095,111111111111,12位
 
    private long lastTimestamp = -1L;
    
    public IdWorker(final long workerId) {
        super();
        if (workerId > this.maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format(
                    "worker Id can't be greater than %d or less than 0",
                    this.maxWorkerId));
        }
        this.workerId = workerId;
    }
    
    public long getWorkerid(){
    	return this.workerId;
    }
 
    public synchronized long nextId() {
        long timestamp = this.timeGen();
        if (this.lastTimestamp == timestamp) {
            this.sequence = (this.sequence + 1) & this.sequenceMask;
            if (this.sequence == 0) {
                System.out.println("###########" + sequenceMask);
                timestamp = this.tilNextMillis(this.lastTimestamp);
            }
        } else {
            this.sequence = 0;
        }
        if (timestamp < this.lastTimestamp) {
            try {
                throw new Exception(
                        String.format(
                                "Clock moved backwards.  Refusing to generate id for %d milliseconds",
                                this.lastTimestamp - timestamp));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
 
        this.lastTimestamp = timestamp;
        long nextId = ((timestamp - twepoch << timestampLeftShift))
                | (this.workerId << this.workerIdShift) | (this.sequence);
//      System.out.println("timestamp:" + timestamp + ",timestampLeftShift:"
//              + timestampLeftShift + ",nextId:" + nextId + ",workerId:"
//              + workerId + ",sequence:" + sequence);
        return nextId;
    }
 
   /* private static IdWorker flowIdWorker = new IdWorker(1);
    public static IdWorker getFlowIdWorkerInstance() {
        return flowIdWorker;
    }*/
    
    private long tilNextMillis(final long lastTimestamp) {
        long timestamp = this.timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = this.timeGen();
        }
        return timestamp;
    }
 
    private long timeGen() {
        return System.currentTimeMillis();
    }
     
     
    public static void main(String[] args){
        
    }
 
}
